﻿using System;
using System.Collections;
using System.Reflection;
using Microsoft.Office.Interop.Word;

namespace XD.Office
{
    public partial class DocTemplateExporter
    {

        /// <summary>
        /// 导出数据卡
        /// </summary>
        /// <param name="object">数据实体</param>
        /// <param name="docFile">输出文件</param>
        /// <returns></returns>
        public bool ExportDataCar(object entity)
        {
            bool ok = false;

            object missing = Type.Missing;
            try
            {
                OpenDocument();

                Replace(entity, _doc);

                ok = true;

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }

            return ok;
        }

        /// <summary>
        /// 导出数据表
        /// </summary>
        /// <param name="table"></param>
        /// <param name="docFile"></param>
        /// <returns></returns>
        public bool ExportData(IEnumerable entityList)
        {
            //获取枚举对象
            IEnumerator enumerator = entityList.GetEnumerator();
            //判断是否空列表
            if (!enumerator.MoveNext())
            {
                return false;
            }

            bool ok = false;

            object missing = Type.Missing;
            try
            {
                OpenDocument();

                enumerator.Reset();
                enumerator.MoveNext();
                object firstEntity = enumerator.Current;
                Type tt = firstEntity.GetType();
                //获取列名称
                string[] columns = GetColumns(firstEntity);
                //获取表格
                Table dataRange = GetDocTable(_doc, _app, columns);

                int iRow = 0;
                enumerator.Reset();
                while (enumerator.MoveNext() && iRow <= _param.MaxRows)
                {
                    object entity = enumerator.Current;
                    Row row = null;
                    int rowIndex = _param.StartRow + iRow;
                    if (rowIndex > dataRange.Rows.Count)
                    {
                        //添加新行
                        row = dataRange.Rows.Add(ref missing);
                    }
                    else
                    {
                        row = dataRange.Rows[rowIndex];
                    }

                    for (int col = 0; col < columns.Length; col++)
                    {
                        object v = tt.InvokeMember(columns[col], BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public, null, entity, null);
                        string value = "";
                        if (v != DBNull.Value)
                        {
                            value = Convert.ToString(v);
                        }
                        row.Cells[_param.StartColumn + col].Range.Text = value;
                    }

                    iRow++;
                }

                ok = true;

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
 
            return ok;
        }

        /// <summary>
        /// 导出数据表
        /// </summary>
        /// <param name="table"></param>
        /// <param name="docFile"></param>
        /// <returns></returns>
        public bool ExportCombo(object cardEntity, IEnumerable entityList)
        {
            //获取枚举对象
            IEnumerator enumerator = entityList.GetEnumerator();
            //判断是否空列表
            if (!enumerator.MoveNext())
            {
                return false;
            }

            bool ok = false;

            object missing = Type.Missing;
            try
            {
                OpenDocument();

                enumerator.Reset();
                enumerator.MoveNext();
                object firstEntity = enumerator.Current;
                Type tt = firstEntity.GetType();
                //获取列名称
                string[] columns = GetColumns(firstEntity);
                //获取表格
                Table dataRange = GetDocTable(_doc, _app, columns);

                //替换
                Replace(cardEntity, _doc);

                int iRow = 0;
                enumerator.Reset();
                while (enumerator.MoveNext() && iRow <= _param.MaxRows)
                {
                    object entity = enumerator.Current;
                    Row row = null;
                    int rowIndex = _param.StartRow + iRow;
                    if (rowIndex > dataRange.Rows.Count)
                    {
                        //添加新行
                        row = dataRange.Rows.Add(ref missing);
                    }
                    else
                    {
                        row = dataRange.Rows[rowIndex];
                    }

                    for (int col = 0; col < columns.Length; col++)
                    {
                        object v = tt.InvokeMember(columns[col], BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public, null, entity, null);
                        string value = "";
                        if (v != DBNull.Value)
                        {
                            value = Convert.ToString(v);
                        }
                        row.Cells[_param.StartColumn + col].Range.Text = value;
                    }

                    iRow++;
                }

                ok = true;

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }

            return ok;
        }

        /// <summary>
        /// 替换
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="sheet"></param>
        private void Replace(object entity, Document doc)
        {
            Type tt = entity.GetType();
            PropertyInfo[] proties = tt.GetProperties();
            object missing = Type.Missing;
            object replaceOption = WdReplace.wdReplaceAll;

            foreach (PropertyInfo pi in proties)
            {
                if (!pi.CanRead)
                    continue;
                object v = tt.InvokeMember(pi.Name, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public, null, entity, null);
                object value = "";
                if (v != DBNull.Value)
                {
                    value = Convert.ToString(v);
                }
                //查找字符串
                object oldStr = string.Format(_param.ReplaceRule, pi.Name.ToUpper());
                doc.Content.Find.Text = (string)oldStr;
                doc.Content.Find.Execute(ref oldStr, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                   ref value, ref replaceOption, ref missing, ref missing, ref missing, ref missing);
            }
        }

        /// <summary>
        /// 获取配置字段
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string[] GetColumns(object entity)
        {
            string[] columns = _param.Columns;
            if (columns == null)
            {
                Type tt = entity.GetType();
                PropertyInfo[] proties = tt.GetProperties();

                int index = 0;
                columns = new string[proties.Length];
                foreach (PropertyInfo pi in proties)
                {
                    if (!pi.CanRead)
                        continue;
                    columns[index] = pi.Name;
                    index++;
                }
            }
            return columns;
        }
    }
}
